package handler

import (
	"io/ioutil"
	"net/http"
	"pan/config"
	"pan/db"
	"pan/util"
)

// SignUpHandler: 处理用户注册请求
func SignUpHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		data, err := ioutil.ReadFile("./static/view/signup.html")
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Write(data)
		return
	} else {
		r.ParseForm()
		username := r.Form.Get("username")
		passwd := r.Form.Get("password")
		if len(username) < 3 || len(passwd) < 5 {
			w.Write([]byte("invalid parameter"))
		}
		encryptPwd := util.Sha1([]byte(passwd + config.PasswordSalt))
		db.UserSignUp(username, encryptPwd)
	}
}

// SignInHandler: 处理用户登录请求
func SignInHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		data, err := ioutil.ReadFile("./static/view/signin.html")
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Write(data)
		return
	} else {
		r.ParseForm()
		username := r.Form.Get("username")
		passwd := r.Form.Get("password")
		encryptPwd := util.Sha1([]byte(passwd + config.PasswordSalt))
		pwdIsOk := db.UserSignIn(username, encryptPwd)
		if !pwdIsOk {
			w.Write([]byte("login fail"))
			return
		}
		token := util.GetToken(username)
		res := db.UpdateToken(username, token)
		if !res {
			w.Write([]byte("update token fail"))
			return
		}
		resp := util.RespMsg{
			Code: 0,
			Msg:  "ok",
			Data: struct {
				Location string
				Username string
				Token    string
			}{
				Location: "http://" + r.Host + "/static/view/home.html",
				Username: username,
				Token:    token,
			},
		}
		w.Write(resp.JSONBytes())
	}
}

func UserInfoHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	// token := r.Form.Get("token")
	// isTokenValid := db.ValidUserToken(username, token)
	// if !isTokenValid {
	// 	w.WriteHeader(http.StatusForbidden)
	// 	return
	// }
	user, err := db.GetUserInfo(username)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	resp := util.RespMsg{
		Code: 0,
		Msg:  "ok",
		Data: user,
	}
	w.Write(resp.JSONBytes())
}
